﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="MoveUsings.cs" company="StyleCop for ReSharper Development Team">
//   Copyright (c) StyleCop for ReSharper Development Team. All rights reserved.
// </copyright>
// <summary>
//   BulbItem - MoveUsings : Moves Using statements inside the clsoest namespace.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace StyleCop.For.ReSharper.BulbItems.Ordering
{
    #region Using Directives

    using JetBrains.ProjectModel;
    using JetBrains.ReSharper.Psi.CSharp.Tree;
    using JetBrains.TextControl;

    using StyleCop.For.ReSharper.BulbItems.Framework;
    using StyleCop.For.ReSharper.Core;

    #endregion

    /// <summary>
    /// BulbItem - MoveUsings : Moves Using statements inside the clsoest namespace.
    /// </summary>
    internal class MoveUsings : V5BulbItemImpl
    {
        public override void ExecuteTransactionInner(ISolution solution, ITextControl textControl)
        {
            var element = Utils.GetElementAtCaret(solution, textControl);

            if (element == null)
            {
                return;
            }

            var usingList = element.GetContainingElement(typeof(IUsingListNode), false) as IUsingListNode;

            if (usingList == null)
            {
                return;
            }

            var file = Utils.GetCSharpFile(solution, textControl);

            // This violation will only run if there are some using statements and definately at least 1 namespace
            // so [0] index will always be OK.
            var firstNamespace = file.NamespaceDeclarations[0];

            foreach (var usingDirectiveNode in usingList.Imports)
            {
                firstNamespace.AddImportBefore(usingDirectiveNode, null);

                file.RemoveImport(usingDirectiveNode);
            }
        }
    }
}